package com.wyz.note.project.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 控制器
 * @Author: wei yz
 * @Date: 2023/5/19 14:13
 */

@RestController
public class StockForRedissonController {
    @Autowired
    private Redisson redisson;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 模拟减库存
     *
     * @return ""
     */
    @PostMapping("/deduct_stock")
    public String deductStock() {
        String lockKey = "lockKey";

        // 获取到redisson锁对象
        RLock redissonLock = redisson.getLock(lockKey);
        try {
            // ========= 添加redisson锁并实现锁续命功能 =============
            /**
             *  主要执行一下几个操作
             *
             *  1、将localKey设置到Redis服务器上，默认过期时间是30s
             *  2、每10s触发一次锁续命功能
             */
            // lock()方法自带30s的看门狗功能！如果使用tryLock（long waitTime, long leaseTime, TimeUnit unit）, 看门狗功能会失效
            redissonLock.lock();
            boolean locked = redissonLock.isLocked();
            System.out.println(" 锁： " + locked);
            // ======== 扣减库存业务员开始 ============
            // 从redis获取库存数量
            String stockStr = String.valueOf(stringRedisTemplate.opsForValue().get("stock"));
            int stock = Integer.parseInt(stockStr);
            // 如果库存数量大于0
            if (stock > 0) {
                int realStock = stock - 1;
                // 相当于jedis.set(key, value)
                stringRedisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println("扣减成功，剩余库存：" + realStock + "");
            } else { // 如果库存数量小于0
                System.out.println("扣减失败，库存不足！");
            }
            // ======== 扣减库存业务员结束 ============
        } finally { // 防止异常导致锁无法释放！！！
            // ============= 释放redisson锁 ==========
            redissonLock.unlock();
        }

        return "end";
    }

}
